package com.zaofan.mobile.control;

import com.google.gson.reflect.TypeToken;
import com.zaofan.bean.AdImg;
import com.zaofan.bean.Address;
import com.zaofan.bean.Comment;
import com.zaofan.bean.OpenArea;
import com.zaofan.bean.OpenBuilder;
import com.zaofan.bean.OpenCity;
import com.zaofan.bean.Product;
import com.zaofan.bean.ProductClass;
import com.zaofan.bean.Reply;
import com.zaofan.cache.CacheManage;
import com.zaofan.constant.UrlConstant;
import com.zaofan.dao.OpenBuilderDao;
import com.zaofan.dao.ProductTypeDao;
import com.zaofan.mobile.bean.Account;
import com.zaofan.mobile.bean.HotelInfo;
import com.zaofan.mobile.bean.ProductDetailParm;
import com.zaofan.mobile.bean.ShopCar;
import com.zaofan.service.AccountService;
import com.zaofan.service.AdImgService;
import com.zaofan.service.CommentService;
import com.zaofan.service.HotelService;
import com.zaofan.service.OpenBuilderService;
import com.zaofan.service.OpenCityService;
import com.zaofan.service.ProductService;
import com.zaofan.service.ReplyService;
import com.zaofan.service.UserFollowService;
import com.zaofan.service.remote.RemoteService;
import com.zaofan.utils.C3p0DataSourceUtils;
import com.zaofan.utils.GsonUtils;
import com.zaofan.utils.HTTPClient;
import com.zaofan.utils.JsonUtils;

import org.apache.commons.beanutils.BeanUtils;
import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanHandler;
import org.apache.commons.dbutils.handlers.MapHandler;
import org.apache.commons.dbutils.handlers.MapListHandler;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;

import java.io.IOException;
import java.net.URLEncoder;
import java.sql.SQLException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * Created by Administrator on 2016/5/25.
 */
@Controller
@RequestMapping("home")
public class HomeController {
	
	private RemoteService remoteService = new RemoteService();
	private AdImgService adImgService = new AdImgService();
    private UserFollowService userFollowService = new UserFollowService();
    private HotelService hotelService = new HotelService();
    private AccountService accountService = new AccountService();
    private OpenBuilderDao openBuilderDao = new OpenBuilderDao();
	
	private static final Logger logger = LoggerFactory.getLogger(HomeController.class);

    @RequestMapping("/beforelogin/index.do")
    public String index(HttpServletRequest request,ModelMap modelMap){
        ProductService productService = new ProductService();
        QueryRunner qr = new QueryRunner(C3p0DataSourceUtils.getDataSource());
        Map<String, Object> current = null;
//        List<Map<String, Object>> qualityPros = null;
        List<Map<String, Object>> productClasses = null;
        try {
            Account account = (Account) request.getSession().getAttribute("userinfo");
            String cityId = request.getParameter("cityId");
            if (cityId == null) {

            	cityId = request.getSession().getAttribute("rechargeCityId") == null 
            			? "1" 
            			: request.getSession().getAttribute("rechargeCityId").toString();
            }

            if (cityId != null && account != null){
                //更新当前所在位置
                qr.update("update currentarea set builderid = ? where userid = ?",new Object[]{cityId,account.getId()});
            }
            if (account != null) {
//                current = qr.query("select builderid,builderName,cityId,cityName,areaId from currentarea left join openbuilder on  currentarea.builderid = openbuilder.id where userid = " + account.getId(), new MapHandler());
                current = qr.query("select opencity.id,cityName from currentarea left join opencity on  currentarea.builderid = opencity.id where userid = ?", new MapHandler(),new Object[]{account.getId()});
                Address address = qr.query("select * from address where accountId = ? and isDefault = 'y'",new BeanHandler<>(Address.class),new Object[]{account.getId()});
                request.getSession().setAttribute("address",address);
            }
            //若无初始位置，则选数据库第一条位置为初始位置
            if (current == null || current.isEmpty()){
                current = new HashMap<>();
                Map<String,Object> temp = qr.query("select * from opencity where cityName like '%福州%'",new MapHandler());
//                current.put("builderid",temp.get("id"));
//                current.put("builderName",temp.get("builderName"));
                current.put("id",temp.get("id"));
                current.put("cityName",temp.get("cityName"));
                if (cityId != null) {
                	Map<String,Object> temp1 = qr.query("select * from opencity where id = " + cityId,new MapHandler());
                	current.put("id",cityId);
                	current.put("cityName",temp1.get("cityName"));
                }
//                current.put("areaId",temp.get("areaId"));

                //初始所在位置
                if (account != null)
                    qr.update("insert into currentarea(builderid,userid) value(?,?)",new Object[]{temp.get("id"),account.getId()});
            }
//            productClasses = qr.query("SELECT productclass.id,classId,className,classOrder,classImage,closetime,detailImage,IF(ISNULL(SUM(dateCount)),0,SUM(dateCount)) AS sellcount FROM productclass " +
//                    "LEFT JOIN product ON product.productClassId = productclass.id where productclass.isopen = 1 "
//                    + " and productclass.cityId = " + cityId + " GROUP BY classOrder", new MapListHandler());

            productClasses = qr.query("SELECT productclass.id,className,classOrder,productclass.type," +
                    " CONCAT('"+ UrlConstant.HOST_URL +"',classImage) as classImage,concat(closetime,' ') as closetime," +
                    " CONCAT('"+ UrlConstant.HOST_URL +"',detailImage) as detailImage," +
                    " IF(ISNULL(SUM(dateCount)),0,SUM(dateCount)) AS sellcount FROM productclass " +
                    " LEFT JOIN product ON product.productClassId = productclass.id where productclass.isopen = 1 "
                    + " and productclass.cityId = " + cityId
                    + " GROUP BY productclass.id  ORDER BY classOrder ", new MapListHandler());

            //精品推荐
//            qualityPros = qr.query("select product.id,name,image,bigImage,price,shopId from product left join shop on shop.id = product.shopId where (areaId = ? or coverType = 1) and isQuality = 1",new MapListHandler(),new Object[]{current.get("areaId")});

	        ProductTypeDao dao = new ProductTypeDao();
	//        List<ProductClass>  = dao.findAll(new HashMap<String, Object>());
            List<AdImg> adimglist=   adImgService.filterByCity(CacheManage.centerAd, Integer.valueOf(cityId));

            //手动添加一张图片
            AdImg adImg = new AdImg();
            adImg.setPicture("http://static.52letsgo.cn/zz/wechat_banner.jpg");
            adImg.setLinkUrl("http://m.52letsgo.com/themes/default/saomiao.php");
            adimglist.add(adImg);
            //手动添加一张图片
            modelMap.put("userinfo",account);
	        modelMap.put("centerAd",adimglist);
	        modelMap.put("title", "首页");
			//modelMap.put("products", remoteService.getZhouTaoCan(Integer.valueOf(cityId)));
	        modelMap.put("productClasses",productClasses);
	//        modelMap.put("qualityPros",qualityPros);
	        request.getSession().setAttribute("area",current);
	        request.getSession().setAttribute("rechargeCityName",current.get("cityName"));
	        request.getSession().setAttribute("rechargeCityId", cityId);
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return "/home/index";
    }

    /**
     * 选择开通区域
     * @param openArea
     * @param modelMap
     * @return
     */
    @RequestMapping("/chooseArea.do")
    public String chooseArea(HttpServletRequest request,OpenArea openArea,ModelMap modelMap){
        OpenCityService cityService = new OpenCityService();

        request.getSession().setAttribute("chooseAreaName",request.getParameter("name"));
        request.getSession().setAttribute("chooseAreaPhone",request.getParameter("phone"));


        try {
            OpenCity city = cityService.findById(openArea.getCityId());
//            if(city == null){
//                JsonUtils.writeListFailJson("对不起,暂未开通该城市,请选择其他城市试试!!", response);
//                return;
//            }
            Map<String,Object> current = (Map<String, Object>) request.getSession().getAttribute("area");
            current.put("cityId",city.getId());
            current.put("cityName",city.getCityName());

            request.getSession().setAttribute("area",current);
            if (CacheManage.openAreas.containsKey(city.getId())) {
                modelMap.put("openarea", CacheManage.openAreas.get(city.getId()));
            } else {
                modelMap.put("openarea",Collections.EMPTY_LIST);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return "/home/chooseArea";
    }

    /**
     * 选择开通大楼
     * @return
     */
    @RequestMapping("/chooseBuilder.do")
    public String chooseBuilder(OpenArea openArea,ModelMap modelMap){
        OpenBuilderService builderService = new OpenBuilderService();
        try {
            if (StringUtils.isEmpty(openArea.getAreaName())){
                if (CacheManage.openBuilders.containsKey(openArea.getId())) {
                    modelMap.put("builders", CacheManage.openBuilders.get(openArea.getId()));
                    modelMap.put("title", CacheManage.openBuilders.get(openArea.getId()).get(0).getAreaName());
                } else {
                    modelMap.put("builders",Collections.EMPTY_LIST);
                }
            }else {
                List<OpenBuilder> builders = builderService.findByNameLike(openArea.getAreaName(), null);
                modelMap.put("builders",builders);
                modelMap.put("title", "大楼搜索结果");
            }


        } catch (Exception e) {
            e.printStackTrace();
        }
        return "/home/chooseBuilder";
    }

    /**
     * 选择开通城市
     * @return
     */
    @RequestMapping("/chooseCity.do")
    public String chooseCity(ModelMap modelMap,HttpServletRequest request){
          String lastpage = request.getParameter("lastpage");

        if (null!=lastpage && lastpage.equals("chooseArea")){
            lastpage="/home/chooseArea.do";
        }else if (null!=lastpage && lastpage.equals("register")){
            lastpage="/wechat/login/register.jsp";
        }
        else{
            lastpage="/home/beforelogin/index.do";
        }

        try {
            modelMap.put("citys",CacheManage.openCities);
            modelMap.put("title","地区");
            modelMap.put("lastpage",lastpage);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return "/home/chooseCity";
    }

    /**
     * 分类产品列表
     * @return
     */
    @RequestMapping("/beforelogin/productList.do")
    public String productList(HttpServletRequest request,ProductClass productClass,String sellcount,String closetime,ModelMap modelMap){
        QueryRunner qr = new QueryRunner(C3p0DataSourceUtils.getDataSource());
        ProductTypeDao productTypeDao = new ProductTypeDao();
        ProductClass currentPtype = null;
        Map<String, Object> current = null;
        List<Map<String, Object>> weekday = null;
        List<Map<String, Object>> pros = null;
        String hotelNo = "";
        try {
            current = (Map<String, Object>) request.getSession().getAttribute("area");
            if (current == null){
                return "/login/index";
            }
            pros = qr.query("select product.id,name,image,categoryId,product.des,bigImage,price,shopId,className,sellcount,product.productClassId from product " +
                    "left join shop on shop.id = product.shopId " +
                    "left join productclass on productclass.id = product.productClassId " +
                    "where (shop.cityId = ? or coverType = 1) and productClassId = ? and product.state = 0 and shop.isOpen = 1 and shop.state = 0 order by product.sort desc,product.addtime asc limit 0,8",new MapListHandler(),new Object[]{current.get("cityId"),productClass.getClassId()});
            Collections.reverse(pros);



            Map<String,Object> parm = new HashMap<>();
            parm.put("id",productClass.getClassId());
            currentPtype = productTypeDao.findOne(parm);
            String tablename = "sendDate";
            //如果是酒店入口
// TODO 酒店注释
            if(null  != request.getSession().getAttribute("isHotel")){
                String isHotel =   request.getSession().getAttribute("isHotel").toString();
                hotelNo = request.getSession().getAttribute("hotelNo").toString();
                if(isHotel.equals("1")) {
                    tablename = "t_hotel_senddate";
//                    pros = qr.query("select product.id,name,concat(hotelImage,'') as image,categoryId,product.des,bigImage,concat(hotelPrice,'') as price,shopId,className,sellcount,product.productClassId from product " +
//                            "left join shop on shop.id = product.shopId " +
//                            "left join productclass on productclass.id = product.productClassId " +
//                            "where (shop.cityId = ? or coverType = 1) and productClassId = ? and product.state = 0 and shop.isOpen = 1 and shop.state = 0 order by product.sort desc,product.addtime asc limit 0,8",new MapListHandler(),new Object[]{current.get("cityId"),productClass.getClassId()});
//                    logger.info("酒店的产品"+pros.toString());
//                    Collections.reverse(pros);
//                    //
                }
            }

            weekday = qr.query("SELECT DATE_FORMAT(sdate,'%Y-%m-%d') as rdate,DATE_FORMAT(sdate,'%m-%d') as date," +
                    "CASE " +
                    "WHEN DAYOFWEEK(sdate) = 1 THEN '周日'" +
                    "WHEN DAYOFWEEK(sdate) = 2 THEN '周一'" +
                    "WHEN DAYOFWEEK(sdate) = 3 THEN '周二'" +
                    "WHEN DAYOFWEEK(sdate) = 4 THEN '周三'" +
                    "WHEN DAYOFWEEK(sdate) = 5 THEN '周四'" +
                    "WHEN DAYOFWEEK(sdate) = 6 THEN '周五'" +
                    "WHEN DAYOFWEEK(sdate) = 7 THEN '周六' " +
                    "END weekName," +
                    "IF(sdate<=DATE_FORMAT(NOW(),'%Y-%m-%d'),'disabled','') AS state " +
                    "FROM "+tablename+" order by sdate",new MapListHandler());
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
            Date now = new Date();
            //遍历找出第一个大于当前日期的选项
            for (Map<String, Object> item : weekday) {
                try {
                    Date wdate = sdf.parse(item.get("rdate")+"");
                    if (wdate.after(now)){
                        item.put("state","checked");
                        break;
                    }
                } catch (ParseException e) {
                    e.printStackTrace();
                }
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }

//        如果是酒店

        modelMap.put("products",pros);
        modelMap.put("week",weekday);
        modelMap.put("title",currentPtype.getClassName());
        modelMap.put("productClass",currentPtype);
        modelMap.put("scout",sellcount);
        modelMap.put("hotelNo",hotelNo);
        if ( currentPtype.getClassName().contains("逼格") || currentPtype.getClassName().contains("进口"))
            return "/home/sproductList";
        else if (currentPtype.getClassName().contains("一元购")){
            return "/home/yiyuanproductList";
        }
        else {
            return "/home/productList";
        }
    }
    /**
     * 产品详情
     * @return
     */
    @RequestMapping("/beforelogin/productDetail.do")
    public String productDetail(Product product, ProductDetailParm detailParm, ModelMap modelMap){
        ProductService productService = new ProductService();

        Product p = null;
        try {
            p = productService.findById(product.getId());
            modelMap.put("product",p);
            modelMap.put("rdate",detailParm.getRdate());
            modelMap.put("productClassId",detailParm.getProductClassId());
            modelMap.put("title","产品详情");
        } catch (Exception e) {
            e.printStackTrace();
        }
        if (Integer.valueOf(detailParm.getType())<2) {
            if (detailParm.getType().equals("0"))

                modelMap.put("backBt","/home/beforelogin/productList.do?classId="+p.getProductClassId()+"&sellcount="+detailParm.getSellcount()+"");
            return "/home/productDetail";
        }else{
            CommentService commentService = new CommentService();
            ReplyService replyService = new ReplyService();

            try {
                int goodsId = product.getId();
                int begin = 0;
                int end = 10;
                try {
                    begin = Integer.valueOf(detailParm.getBegin_s());
                } catch (Exception e) {
                    begin = 0;
                    e.printStackTrace();
                }
                try {
                    end = Integer.valueOf(detailParm.getEnd_s());
                } catch (Exception e) {
                    end = 0;
                    e.printStackTrace();
                }
                List<com.zaofan.mobile.bean.Comment> datas = new ArrayList<>();
                com.zaofan.mobile.bean.Comment comment = null;
                List<Comment> comments = commentService.findProductComments(goodsId, begin, end);
                for (Comment item : comments) {
                    comment = new com.zaofan.mobile.bean.Comment();
                    BeanUtils.copyProperties(comment, item);
                    if (comment.getIsReply() == 1) {
                        Reply reply = replyService.findByCommentId(comment.getId());
                        comment.setReply(reply);
                    }
                    if (comment.getUserPhoto() != null && !"".equals(comment.getUserPhoto())) {
                        comment.setUserPhoto(UrlConstant.HOST_URL + comment.getUserPhoto());
                    }
                    datas.add(comment);
                }
                modelMap.put("comments",datas);
            } catch (Exception e) {
                e.printStackTrace();
            }
            return "/home/sproductDetail";
        }
    }

    @RequestMapping("/deleteShopCar.do")
//    @ResponseBody
    public void deleteShopCar(HttpServletRequest request, String key, int index, HttpServletResponse response){
        Map<String,List<Map<String,String>>> shopcar = (Map<String, List<Map<String, String>>>) request.getSession().getAttribute("shopCar");
        ShopCar totalSC = (ShopCar) request.getSession().getAttribute("totalSC");
        try {
            List<Map<String,String>> list = shopcar.get(key);
            int totalCount = Integer.valueOf(list.get(index).get("goodAccount"));
            double totalPrice = Double.valueOf(list.get(index).get("goodPrcie"))*totalCount;
            totalSC.setTotalPrice(totalSC.getTotalPrice()-totalPrice);
            totalSC.setTotalCount(totalSC.getTotalCount()-totalCount);
            //删除最后一件商品 清空购物车
            if (totalSC.getTotalCount() == 0){
                request.getSession().removeAttribute("shopCar");
                request.getSession().removeAttribute("totalSC");
                JsonUtils.writeSuccessJson("删除成功", "", response);
                return;
            }
            shopcar.put(key,list);
            list.remove(index);
            request.getSession().setAttribute("shopCar",shopcar);
            request.getSession().setAttribute("totalSC",totalSC);
            JsonUtils.writeSuccessJson("删除成功", "", response);
        }catch (Exception e){
            JsonUtils.writeFailJson("删除失败",response);
        }
    }

    @RequestMapping("/cleanShopCar.do")
//    @ResponseBody
    public void cleanShopCar(HttpServletRequest request,HttpServletResponse response){
        try {
            request.getSession().removeAttribute("shopCar");
            request.getSession().removeAttribute("totalSC");
            JsonUtils.writeSuccessJson("删除成功", "", response);
        }catch (Exception e){
            JsonUtils.writeFailJson("删除失败",response);
        }
    }

    /**
     * 购物车
     * @return
     */
    @RequestMapping("/shopCar.do")
    public String shopCar(HttpServletRequest request,ShopCar sc, ModelMap modelMap){
        Map<String,List<Map<String,String>>> shopcar = (Map<String, List<Map<String, String>>>) request.getSession().getAttribute("shopCar");
        ShopCar totalSC = (ShopCar) request.getSession().getAttribute("totalSC");

        if (totalSC == null && sc != null){
            request.getSession().setAttribute("totalSC",sc);
        }else if (sc != null){
            totalSC.setTotalCount(totalSC.getTotalCount()+sc.getTotalCount());
            totalSC.setTotalPrice(totalSC.getTotalPrice()+sc.getTotalPrice());
            request.getSession().setAttribute("totalSC",totalSC);
        }

        if (sc != null && !StringUtils.isEmpty(sc.getOrder())){
            if (shopcar == null)
                shopcar = new HashMap<>();
            Map<String,List<Map<String,String>>> orderMap = GsonUtils.getInstance().fromJson(sc.getOrder(),new TypeToken<Map<String,List<Map<String,String>>>>(){}.getType());
            for (Map.Entry<String,List<Map<String,String>>> entry:orderMap.entrySet()) {
                if (shopcar.containsKey(entry.getKey())){
                    List<Map<String,String>> orders = shopcar.get(entry.getKey());
                    orders.addAll(entry.getValue());
                    shopcar.put(entry.getKey(),orders);
                }else {
                    shopcar.put(entry.getKey(),entry.getValue());
                }
            }
            request.getSession().setAttribute("shopCar",shopcar);
        }

        //如果地址为空就往下走
        //如果不为空

        if (request.getSession().getAttribute("address") == null) {
        	QueryRunner qr = new QueryRunner(C3p0DataSourceUtils.getDataSource());
        	Account account = (Account) request.getSession().getAttribute("userinfo");
        	logger.info("用户信息：{}", account);
        	Address address = null;
        	try {
        		address = qr.query("select * from address where accountId = ? and isDefault = 'y'",new BeanHandler<>(Address.class),new Object[]{account.getId()});
        		if (address == null) {
        			address = qr.query("select * from address where accountId = ? limit 1",new BeanHandler<>(Address.class),new Object[]{account.getId()});
        		}
        		logger.info("地址信息：{}", address);
        	} catch (SQLException e) {
        		e.printStackTrace();
        	}


            if (null !=  request.getSession().getAttribute("hotelBuilder")){
                OpenBuilder hotelBuilder = (OpenBuilder) request.getSession().getAttribute("hotelBuilder");
                address = new Address();
                HotelInfo hotelInfo = (HotelInfo) request.getSession().getAttribute("hotelInfo");
                address.setBuilderId(hotelBuilder.getId());
                address.setBuilderName(hotelBuilder.getBuilderName());
                address.setCityId(hotelBuilder.getCityId());
                address.setCityName(hotelBuilder.getCityName());
                address.setFloorNo("酒店");
                address.setAreaId(hotelBuilder.getAreaId());
                address.setAreaName(hotelBuilder.getAreaName());
                address.setAddress(hotelBuilder.getBuilderName());
                String hotelNo = (String) request.getSession().getAttribute("hotelNo");
                modelMap.put("hotelNo",hotelNo);
                modelMap.put("hotelInfo", request.getSession().getAttribute("hotelInfo"));
                modelMap.put("isHotel", request.getSession().getAttribute("isHotel"));
            }
            modelMap.put("address",address);
        	request.getSession().setAttribute("address",address);


        }


        if(request.getSession().getAttribute("CouponUserId") !=null && request.getSession().getAttribute("CouponId") !=null ){
            String CouponUserId = (String) request.getSession().getAttribute("CouponUserId");
            String CouponId = (String) request.getSession().getAttribute("CouponId");
            String CouponName = (String) request.getSession().getAttribute("CouponName");
            System.out.println("选择的优惠券"+CouponUserId);
            if (!CouponUserId.equals("0") && !CouponId.equals("0") ){
                modelMap.put("CouponUserId",CouponUserId);
                modelMap.put("CouponId",CouponId);
                modelMap.put("CouponName",CouponName);
            }
        }




        modelMap.put("title","购物车");
        return "/home/shopCar";
    }
    /**
     * 获取产品评论
     * @return
     */
    @RequestMapping("/beforelogin/productComment.do")
    public String productComment(Product product,String begin_s,String end_s, ModelMap modelMap){
        modelMap.put("product",product);
        modelMap.put("title","产品评价");
        return "/home/productComment";
    }

    @RequestMapping("/beforelogin/hotel_entry.do")
    public String hotel_login(ModelMap modelMap,HttpServletRequest request,HttpServletResponse response) throws IOException, SQLException {
        logger.info("Hotel entry-----------------");


        String hotelNo = request.getParameter("hotelNo");


        String redirect_url = "http://m.52letsgo.cn/home/beforelogin/hotel_entry.do?hotelNo="+hotelNo;

        String code  =  request.getParameter("code");
        if(code == null || code.equals("")){
            String http = "https://open.weixin.qq.com/connect/oauth2/authorize?";
            String appid = "&appid=wxf946190506655c2d";
            String redirect_uri = "&redirect_uri=" +
                    URLEncoder.encode(redirect_url, "utf8");
            String response_type = "&response_type=code";
            String scope = "&scope=snsapi_base";
            String state = "&state=16516516156#wechat_redirect";
            return "redirect:"+http + appid + redirect_uri + response_type + scope + state;
        }
        System.out.println("--------code-------"+code+"----------");
        String url = "https://api.weixin.qq.com/sns/oauth2/access_token" +
                "?appid=wxf946190506655c2d"+
                "&secret=25f4e517eeea25ea18e75cab31cc3b8b" +
                "&grant_type=authorization_code" +
                "&code=" + code;

        String openid = "";

        String result = HTTPClient.postJson(url, "");
        if (StringUtils.isNoneEmpty(result)) {
            HashMap map = GsonUtils.fromJson(result, HashMap.class);
            openid = map.get("openid").toString();
        }

        //Stringopenid = "GonTest10000";
        request.getSession().removeAttribute("address");
        request.getSession().removeAttribute("isHotel");
        request.getSession().removeAttribute("area");
        request.getSession().removeAttribute("rechargeCityName");
        request.getSession().removeAttribute("rechargeCityId");
        request.getSession().removeAttribute("hotelBuilder");
        request.getSession().removeAttribute("hotelInfo");
        request.getSession().removeAttribute("userinfo");
        request.getSession().removeAttribute("hotelNo");
        request.getSession().removeAttribute("openid");
        //清空购物车session
        request.getSession().removeAttribute("shopCar");
        request.getSession().removeAttribute("totalSC");

        hotelService.deleteUserAddressByOpenId(openid);
        // 是否清空用户地址


        request.getSession().setAttribute("openid",openid);

        logger.info("Hotel entry id-----------------"+openid);
        logger.info("Hotel entry no-----------------"+hotelNo);

        if (StringUtils.isEmpty(hotelNo)){
            //登录页面
            logger.error("hotelNo为空");
            return "redirect:"+"http://m.52letsgo.cn/login.do";
        }
        HotelInfo hotelInfo = hotelService.findOpenHotelByHotelNo(hotelNo);
        if(null==hotelInfo){
            //登录页面
            logger.error("酒店信息为空");
            return "redirect:"+"http://m.52letsgo.cn/login.do";
        }
        hotelService.incScanByHotelNo(hotelNo);


        com.zaofan.bean.Account account =accountService.findByMobile(openid);

        Account Wxaccount = new Account();

        if (account == null){
            logger.info( " hotel account "+account);
            accountService.quicklyRegister(openid,hotelNo,response);
            account =  accountService.findByMobile(openid);
            logger.info( " hotel account "+account.toString());

            if (account==null){
                logger.error("acount为空");
                return "redirect:"+"http://m.52letsgo.cn/login.do";
            }

        }



        Wxaccount.setMobile(account.getMobile());
        Wxaccount.setMoney(account.getMoney());
        Wxaccount.setBuilderId(account.getBuilderId());
        Wxaccount.setBuilderName(account.getBuilderName());
        Wxaccount.setCityId(account.getCityId());
        Wxaccount.setCityName(account.getCityName());
        Wxaccount.setLastLoginTime(account.getLastLoginTime());
        Wxaccount.setNickname(account.getNickname());
        Wxaccount.setRegeistDate(account.getRegeistDate());
        Wxaccount.setId(account.getId());



        Map<String, Object> current = new HashMap<>();
        OpenBuilder openBuilder = openBuilderDao.findByAddressId(hotelInfo.getAddressId());
        current.put("id",  openBuilder.getCityId());
        current.put("cityName",  openBuilder.getCityName());


        List<Map<String, Object>> productClasses = new ArrayList<>();
        QueryRunner qr = new QueryRunner(C3p0DataSourceUtils.getDataSource());
        productClasses = qr.query("SELECT productclass.id,className,classOrder,productclass.type," +
                " CONCAT('"+ UrlConstant.HOST_URL +"',classImage) as classImage,concat(closetime,' ') as closetime," +
                " CONCAT('"+ UrlConstant.HOST_URL +"',detailImage) as detailImage," +
                " IF(ISNULL(SUM(dateCount)),0,SUM(dateCount)) AS sellcount FROM productclass " +
                " LEFT JOIN product ON product.productClassId = productclass.id where productclass.isopen = 1 "
                + " and productclass.cityId = " + openBuilder.getCityId()
                + " GROUP BY productclass.id  ORDER BY classOrder ", new MapListHandler());
        if("didi".equals(hotelNo)){
            List<Map<String, Object>> didiClasses = new ArrayList<>();
            didiClasses = qr.query("SELECT productclass.id,className,classOrder,productclass.type," +
                    " CONCAT('"+ UrlConstant.HOST_URL +"',classImage) as classImage,concat(closetime,' ') as closetime," +
                    " CONCAT('"+ UrlConstant.HOST_URL +"',detailImage) as detailImage," +
                    " IF(ISNULL(SUM(dateCount)),0,SUM(dateCount)) AS sellcount FROM productclass " +
                    " LEFT JOIN product ON product.productClassId = productclass.id " +
                    "where productclass.className  = '三八女王'"
//                    "where productclass.className = '滴滴打滴' "
                    + " and productclass.cityId = " + openBuilder.getCityId()
                    + " GROUP BY productclass.id  ORDER BY classOrder ", new MapListHandler());


            didiClasses.addAll(productClasses);
            productClasses = didiClasses;
            logger.info("滴滴进入的产品列表长度"+productClasses.size());
        }

        List<AdImg> adimglist=   adImgService.filterByCity(CacheManage.centerAd, openBuilder.getCityId());
        //手动添加一张图片
        AdImg adImg = new AdImg();
        adImg.setPicture("http://static.52letsgo.cn/zz/wechat_banner.jpg");
        adImg.setLinkUrl("http://m.52letsgo.com/themes/default/saomiao.php");
        adimglist.add(adImg);

        request.getSession().setAttribute("hotelNo",hotelNo);
        request.getSession().setAttribute("isHotel",1);
        request.getSession().setAttribute("area",current);
        request.getSession().setAttribute("rechargeCityName",current.get("cityName"));
        request.getSession().setAttribute("rechargeCityId", current.get("id"));
        request.getSession().setAttribute("hotelBuilder",openBuilder);
        request.getSession().setAttribute("hotelInfo",hotelInfo);
        request.getSession().setAttribute("userinfo",Wxaccount);
        modelMap.put("hotelNo",hotelNo);
        modelMap.put("productClasses",productClasses);
        modelMap.put("userinfo",account);
        modelMap.put("centerAd",adimglist);
        modelMap.put("title", "首页");
        modelMap.put("hotelInfo", hotelInfo);
        modelMap.put("openid",openid);
        return "/home/index";
    }

    @RequestMapping("/hotelOrderInc.do")
    public void hotelOrderInc(HttpServletRequest request,HttpServletResponse response){
        try {
           String hotelNo = request.getParameter("hotelNo");
           String orderNo = request.getParameter("orderNo");
           String mobile = request.getParameter("mobile");
           String user_address_id = request.getParameter("user_address_id");
            hotelService.incOrderByHotelNo(hotelNo);
            hotelService.addOrder(hotelNo,orderNo,mobile);
            //删除地址


            JsonUtils.writeSuccessJson("酒店下单成功", "", response);
        }catch (Exception e){
            JsonUtils.writeFailJson("酒店下单失败",response);
        }
    }


}
